package com.sendinfo.sso;

import java.util.UUID;

public abstract class UUIDUtil {
	public static byte[] toBytes(UUID uuid) {
		if (null == uuid) return null;
		byte[] data = new byte[16];
		long msb = uuid.getMostSignificantBits();
		long lsb = uuid.getLeastSignificantBits();
		for (int i = 7; i >= 0; i--) {
			data[i] = (byte) (msb & 0xff);
			msb = msb >> 8;
		}
		for (int i = 15; i >= 8; i--) {
			data[i] = (byte) (lsb & 0xff);
			lsb = lsb >> 8;
		}
		return data;
	}

	public static UUID fromBytes(byte[] data) {
		long msb = 0;
		long lsb = 0;
		assert data.length == 16;
		for (int i = 0; i < 8; i++)
			msb = msb << 8 | data[i] & 0xff;
		for (int i = 8; i < 16; i++)
			lsb = lsb << 8 | data[i] & 0xff;
		return new UUID(msb, lsb);
	}

	public static UUID fromHexString(String hex) {
		// TODO should be optimized for performance.
		assert hex.length() == 32;
		String name = hex.substring(0, 8) + "-" + hex.substring(8, 12) + "-" + hex.substring(12, 16) + "-" + hex.substring(16, 20) + "-"
				+ hex.substring(20);
		return UUID.fromString(name);
	}

	/**
	 * 字符串转换UUID
	 * 
	 * @author juror
	 * @date 2008-12-12 上午09:57:45
	 * @param value
	 * @return
	 * @throws Exception
	 */
	public static UUID parseUUID(String value) throws RuntimeException {
		if (value.length() == 32) return fromHexString(value);
		else if (value.length() == 36) {
			return UUID.fromString(value);
		} else throw new RuntimeException("It is not UUID!");

	}

	/**
	 * 字符串UUID判断
	 * 
	 * @author juror
	 * @date 2008-12-12 上午09:58:02
	 * @param value
	 * @return
	 */
	public static boolean isUUID(String value) {
		try {
			parseUUID(value);
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	public static String toHexString(UUID uuid) {
		String hi = Long.toHexString(uuid.getMostSignificantBits());
		String lo = Long.toHexString(uuid.getLeastSignificantBits());
		if (hi.length() == 15) hi = "0" + hi;
		if (lo.length() == 15) lo = "0" + lo;
		return hi + lo;
	}

	public static byte[] toBytesForDB(UUID id) {
		return null == id ? null : toBytes(id);
	}

	public static UUID fromBytesOfDB(byte[] data) {
		if (null == data) return null;
		else if (data.length == 32) return fromHexString(new String(data));
		else if (data.length == 16) return fromBytes(data);
		else return null;
	}
}
